import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'flutter_spectrum_platform_interface.dart';

typedef void EventHandler(dynamic event);

class MethodChannelFlutterSpectrum extends FlutterSpectrumPlatform {
  @visibleForTesting
  final methodChannel = const MethodChannel('flutter_spectrum');

  final EventChannel eventChannel =
      const EventChannel('flutter_spectrum.events');
  StreamSubscription<dynamic>? _subscription;

  final EventChannel playCompleteChannel =
      const EventChannel('flutter_spectrum.play.complete');
  StreamSubscription<dynamic>? _playCompleteSubscription;

  @override
  listenPcm(EventHandler onEvent, EventHandler onError) {
    _subscription?.cancel();
    _subscription =
        eventChannel.receiveBroadcastStream().listen(onEvent, onError: onError);
  }

  @override
  Future<void> startPlay(String filePath) async {
    await methodChannel.invokeMethod<void>('startPlay', {'filePath': filePath});
  }

  @override
  Future<void> stopPlay() async {
    await methodChannel.invokeMethod<void>('stopPlay');
  }

  @override
  Future<void> onPlayCompleted(EventHandler onEvent) async {
    _playCompleteSubscription?.cancel();
    _playCompleteSubscription =
        playCompleteChannel.receiveBroadcastStream().listen(
              onEvent,
            );
  }
}
